﻿using System;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using DAL;
using Utils;
//迁移过来的，BLL里弦这样
namespace BLL
{
    public class DepartmentBiz
    {
        DepartmentDao departmentDao = new DepartmentDao();
        AccountDao accountDao = new AccountDao();
        CheckRight checkRight = new CheckRight();
        //判断一个部门是否存在 存在 true 不存在是 false
        public bool IsExistOneInfo(string name)
        {
            bool flag = true;
            try
            {
                DataSet ds = departmentDao.GetDataSet("Select count(*) as Num from Admin_Department  Where [Name]='" + name + "'");
                if (ds == null)
                    flag = false;
                else
                {
                    if (Int32.Parse(ds.Tables[0].Rows[0]["Num"].ToString()) <= 0)
                        flag = false;

                }
            }
            catch
            {
                flag = false;
            }
            return flag;
        }
        /// <summary>
        /// 初始化企业部门dropDownList
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="dropDownList">下拉列表ID</param>
        public void InitDropDownList(DropDownList dropDownList, string defaultSelectItem)
        {
            try
            {
                string sysType = XmlUtility.GetWebParam("SysType");
                if (sysType == "Mutil")
                    InitMutiDropDownList(dropDownList, defaultSelectItem);
                else
                    InitSingleDropDownList(dropDownList, defaultSelectItem);


            }
            catch (Exception ee)
            {
                LogHelper.WriteLog(ee.Message);
            }
        }
        private void InitSingleDropDownList(DropDownList dropDownList, string defaultSelectItem)
        {
            dropDownList.Items.Clear();
            System.Web.SessionState.HttpSessionState mys = HttpContext.Current.Session;
            int companyID = 0;
            if (mys["user"] != null)
            {
                User user = mys["user"] as User;
                companyID = user.CompanyID;
            }
            dropDownList.Items.Add(new ListItem("请选择部门", "0"));
            DataTable dt = GetLists("select * from Admin_Department Where State='Y' and ParentID=" + companyID + "  order by AbsIndex ASC");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dropDownList.Items.Add(new ListItem(dt.Rows[i]["Name"].ToString(), dt.Rows[i]["DeptID"].ToString()));

            }
            dropDownList.ClearSelection();
            //绑定默认值
            if (defaultSelectItem == "0" || string.IsNullOrWhiteSpace(defaultSelectItem))
                dropDownList.Items[0].Selected = true;
            else
            {

                if (RegexRule.IsInt(defaultSelectItem))
                {
                    for (int jj = 0; jj < dropDownList.Items.Count; jj++)
                    {
                        if (dropDownList.Items[jj].Value == defaultSelectItem)
                        {
                            dropDownList.Items[jj].Selected = true;
                            break;
                        }
                    }
                }
                else
                {
                    for (int jj = 0; jj < dropDownList.Items.Count; jj++)
                    {
                        if (dropDownList.Items[jj].Text == defaultSelectItem)
                        {
                            dropDownList.Items[jj].Selected = true;
                            break;
                        }
                    }
                }
            }

        }
        /// <summary>
        /// 多级部门绑定
        /// </summary>
        /// <param name="dropDownList"></param>
        private void InitMutiDropDownList(DropDownList dropDownList, string defaultSelectItem)
        {
            try
            {
                System.Web.SessionState.HttpSessionState mys = HttpContext.Current.Session;
                int companyID = 0;
                int deptID = 0;
                string account = string.Empty;
                DataTable dt = null;
                if (mys["user"] != null)
                {
                    User user = mys["user"] as User;
                    companyID = user.CompanyID;
                    deptID = user.DepartemntID;
                    account = user.Account;
                }
                //获得所有数据列表,员工自己所在的公司    这里要重新写了
                string url = checkRight.GetRightUrl(account);
                int rangeChar = (int)AccountBiz.GetRange(account, url);
                switch (rangeChar)
                {
                    case 1://显示部门
                    case 2:
                        dt = GetLists("select * from Admin_Department Where State='Y' and ParentID=" + deptID + "  order by AbsIndex ASC");
                        break;
                    case 3://显示公司
                        dt = GetLists("select * from Admin_Department Where State='Y' and ParentID=" + companyID + "  order by AbsIndex ASC");
                        break;
                    case 4:
                    case 5://超级用户显示所有
                        dt = GetLists("select * from Admin_Department Where State='Y'   order by AbsIndex ASC");
                        break;
                    default:
                        dt = GetLists("select * from Admin_Department Where State='Y' and ParentID=" + companyID + "  order by AbsIndex ASC");
                        break;

                }


                dropDownList.Items.Clear();
                dropDownList.Items.Add(new ListItem("选择部门", "0"));
                DataRow[] drs = dt.Select("ParentID= " + 0);

                foreach (DataRow dr in drs)
                {
                    string classid = dr["DeptID"].ToString();
                    string classname = dr["Name"].ToString();
                    //顶级分类显示形式
                    classname = "" + classname;

                    dropDownList.Items.Add(new ListItem(classname, classid));
                    ///////////////////
                    if (defaultSelectItem == "0" || string.IsNullOrWhiteSpace(defaultSelectItem))
                        dropDownList.SelectedValue = "0";
                    else
                    {

                        if (RegexRule.IsInt(defaultSelectItem))
                        {
                            for (int jj = 0; jj < dropDownList.Items.Count; jj++)
                            {
                                if (dropDownList.Items[jj].Value == defaultSelectItem)
                                {
                                    dropDownList.Items[jj].Selected = true;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            for (int jj = 0; jj < dropDownList.Items.Count; jj++)
                            {
                                string itemValue = dropDownList.Items[jj].Text.Trim();
                                string value = StringUtility.RemoveLeftSpace(itemValue);
                                if (value == defaultSelectItem)
                                {
                                    dropDownList.Items[jj].Selected = true;
                                    break;
                                }
                            }
                        }
                    }
                    //////////////////////

                    int sonparentid = int.Parse(classid);
                    string blank = "" + (char)12288;// 32;
                    //递归子分类方法
                    BindNode(sonparentid, dropDownList, dt, blank, defaultSelectItem);
                }
                dropDownList.DataBind();
            }
            catch (Exception ee)
            {
                LogHelper.WriteLog(ee.Message);
            }
        }

        //根据权限显示 下拉列表  比如：根据账号查该账号的业务数据
        public void InitDropDownList(DropDownList dropDownList, string defaultSelectItem, string account, string companyID, string departmentID)
        {

            try
            {
                string parentID;
                DataTable dt = GetRightDept(account, companyID, departmentID, out parentID);

                dropDownList.Items.Clear();
                if (dt == null)
                {
                    dropDownList.Items.Add(new ListItem("选择人员", "EMP$" + account));
                    return;
                }
                if (dt.Rows.Count < 1)
                {
                    dropDownList.Items.Add(new ListItem("选择人员", "EMP$" + account));
                    return;
                }
                DataRow[] drs;
                if (parentID == "0")
                {
                    dropDownList.Items.Add(new ListItem("选择部门", "COM$0"));
                    drs = dt.Select("ParentID= 0");
                }
                else
                    drs = dt.Select("DeptID= " + parentID);
                //DataRow[] drs = dt.Select("ParentID= " + parentID);

                foreach (DataRow dr in drs)
                {
                    string classid = dr["DeptID"].ToString();
                    string classname = dr["Name"].ToString();
                    //顶级分类显示形式
                    classname = "" + classname;

                    dropDownList.Items.Add(new ListItem(classname, "COM$" + classid));
                    //获取部门下的员工账号列表
                    DataTable empDt = accountDao.GetListByDeptID(classid);
                    for (int r = 0; r < empDt.Rows.Count; r++)
                    {
                        dropDownList.Items.Add(new ListItem("" + (char)12288 + empDt.Rows[r]["EmpName"], "Emp$" + empDt.Rows[r]["Account"]));
                    }
                    ///////////////////
                    if (defaultSelectItem == "0")
                    {
                        dropDownList.SelectedValue = "0";
                    }
                    else if (string.IsNullOrWhiteSpace(defaultSelectItem))
                    { }
                    else
                    {

                        if (RegexRule.IsInt(defaultSelectItem))
                        {
                            for (int jj = 0; jj < dropDownList.Items.Count; jj++)
                            {
                                if (dropDownList.Items[jj].Value == defaultSelectItem)
                                {
                                    dropDownList.Items[jj].Selected = true;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            for (int jj = 0; jj < dropDownList.Items.Count; jj++)
                            {
                                string itemValue = dropDownList.Items[jj].Text.Trim();
                                string value = StringUtility.RemoveLeftSpace(itemValue);
                                if (value == defaultSelectItem)
                                {
                                    dropDownList.Items[jj].Selected = true;
                                    break;
                                }
                            }
                        }
                    }
                    //////////////////////

                    int sonparentid = int.Parse(classid);
                    string blank = "" + (char)12288;// 32;


                    //递归子分类方法
                    BindSubNode(sonparentid, dropDownList, dt, blank, defaultSelectItem);
                }
                dropDownList.DataBind();
            }
            catch (Exception ee)
            {
                LogHelper.WriteLog(ee.Message);
            }
        }
        //绑定子节点 并绑定人员
        private void BindSubNode(int parentid, DropDownList dropDownList, DataTable dt, string blank, string defaultSelectItem)
        {
            DataRow[] drs = dt.Select("ParentID= " + parentid);

            foreach (DataRow dr in drs)
            {
                string classid = dr["DeptID"].ToString();
                string classname = dr["Name"].ToString();

                classname = blank + classname;
                dropDownList.Items.Add(new ListItem(classname, "COM$" + classid));
                //获取部门下的员工账号列表
                DataTable empDt = accountDao.GetListByDeptID(classid);
                for (int r = 0; r < empDt.Rows.Count; r++)
                {
                    dropDownList.Items.Add(new ListItem(blank + (char)12288 + empDt.Rows[r]["EmpName"], "Emp$" + empDt.Rows[r]["Account"]));
                }
                ///////////////////
                if (defaultSelectItem == "0" )
                    dropDownList.SelectedValue = "0";
                else if( string.IsNullOrWhiteSpace(defaultSelectItem))
                {}
                else
                {
                    if (RegexRule.IsInt(defaultSelectItem))
                    {
                        for (int jj = 0; jj < dropDownList.Items.Count; jj++)
                        {
                            if (dropDownList.Items[jj].Value == defaultSelectItem)
                            {
                                dropDownList.Items[jj].Selected = true;
                                break;
                            }
                        }
                    }
                    else
                    {
                        for (int jj = 0; jj < dropDownList.Items.Count; jj++)
                        {
                            string itemValue = dropDownList.Items[jj].Text.Trim();
                            string value = StringUtility.RemoveLeftSpace(itemValue);

                            if (value == defaultSelectItem)
                            {
                                dropDownList.Items[jj].Selected = true;
                                break;
                            }
                        }
                    }
                }
                //////////////////////
                int sonparentid = int.Parse(classid);
                string blank2 = blank + (char)12288;
                BindSubNode(sonparentid, dropDownList, dt, blank2, defaultSelectItem);
            }
        }

        private void BindNode(int parentid, DropDownList dropDownList, DataTable dt, string blank, string defaultSelectItem)
        {
            DataRow[] drs = dt.Select("ParentID= " + parentid);

            foreach (DataRow dr in drs)
            {
                string classid = dr["DeptID"].ToString();
                string classname = dr["Name"].ToString();

                classname = blank + classname;
                dropDownList.Items.Add(new ListItem(classname, classid));
                ///////////////////
                if (defaultSelectItem == "0" || string.IsNullOrWhiteSpace(defaultSelectItem))
                    dropDownList.SelectedValue = "0";
                else
                {
                    if (RegexRule.IsInt(defaultSelectItem))
                    {
                        for (int jj = 0; jj < dropDownList.Items.Count; jj++)
                        {
                            if (dropDownList.Items[jj].Value == defaultSelectItem)
                            {
                                dropDownList.Items[jj].Selected = true;
                                break;
                            }
                        }
                    }
                    else
                    {
                        for (int jj = 0; jj < dropDownList.Items.Count; jj++)
                        {
                            string itemValue = dropDownList.Items[jj].Text.Trim();
                            string value = StringUtility.RemoveLeftSpace(itemValue);

                            if (value == defaultSelectItem)
                            {
                                dropDownList.Items[jj].Selected = true;
                                break;
                            }
                        }
                    }
                }
                //////////////////////
                int sonparentid = int.Parse(classid);
                string blank2 = blank + (char)12288;
                BindNode(sonparentid, dropDownList, dt, blank2, defaultSelectItem);
            }
        }
        public DataTable GetCompany()
        { return departmentDao.GetCompany(); }

        public DataTable GetLists()
        {
            return departmentDao.GetLists("select * from Admin_Department Where State='Y' order by AbsIndex ASC");
        }
        public DataTable GetLists(string strSQL)
        {
            return departmentDao.GetLists(strSQL);
        }
        public DataSet GetDataSet(string strRight)
        {
            if (strRight == "SU")
                return departmentDao.GetDataSet("select DeptID,DeptCode,ParentID,Name from Admin_Department order by AbsIndex ASC");
            else
                return departmentDao.GetDataSet("select DeptID,DeptCode,ParentID,Name from Admin_Department where State='Y' order by AbsIndex ASC");
        }
        public DataSet GetDataSet(string procName, SqlParameter[] spList)
        {
            return departmentDao.GetDataSet(procName, spList);
        }
        //public bool ExecSQL(string strSQL)
        //{
        //    return departmentDao.ExecSQL(strSQL);
        //}

        //获取某个账号所在部门的部门属性
        public string GetPropertie(string account)
        {
            DataTable dt = GetLists("Select Propertie From Admin_Department Where DeptID=(select DeptID from JimView_Account Where Account='" + account + "')");
            string strPropertie = "";
            if (dt.Rows.Count > 0)
                strPropertie = dt.Rows[0][0].ToString();
            else
                strPropertie = "000";

            string[] s = strPropertie.Split(',');
            return s[0];
        }

        public string GetPropertie(int deptID)
        {
            DataTable dt = GetLists("Select Propertie From Admin_Department Where DeptID=" + deptID);
            string strPropertie = "";
            if (dt.Rows.Count > 0)
                strPropertie = dt.Rows[0]["Propertie"].ToString();
            else
                strPropertie = "000";

            string[] s = strPropertie.Split(',');
            return s[0];
        }

        //根据登录的部门ID；获取部门的简拼
        public string GetPinSn(int deptID)
        {
            DataTable dt = GetLists("Select PinSn From Admin_Department Where DeptID=" + deptID);
            string pinSn = "";
            if (dt.Rows.Count > 0)
                pinSn = dt.Rows[0]["PinSn"].ToString();
            else
                pinSn = "TM";
            return pinSn.Trim();
        }
        //根据登录的部门ID；获取部门的名称
        public string GetName(int deptID)
        {
            DataTable dt = GetLists("Select [Name] From Admin_Department Where DeptID=" + deptID);
            string pinSn = "";
            if (dt.Rows.Count > 0)
                pinSn = dt.Rows[0]["Name"].ToString();
            return pinSn.Trim();
        }
        //递归获得部门下所有子部门的ID
        //ds是部门表的ds
        //deptID是登陆自己的deptID
        public string GetSubID(DataSet ds, int ParentID)
        {

            string strDeptIDArray = ParentID + ",";


            DataView dvData = new DataView(ds.Tables[0]);
            //过滤ParentID
            dvData.RowFilter = "[ParentID] = " + ParentID;

            foreach (DataRowView Row in dvData)
            {
                strDeptIDArray += Row["DeptID"].ToString() + ",";
                strDeptIDArray += GetSubID(ds, Int32.Parse(Row["DeptID"].ToString()));
            }
            return strDeptIDArray.ToString().Remove(strDeptIDArray.ToString().Length - 1);
        }
        public DataTable GetRightDept(string account, string companyID, string departmentID, out string parentID)
        {
            string url = checkRight.GetRightUrl(account);// HttpContext.Current.Request.Url.AbsolutePath;
            return departmentDao.GetRightDept(account, companyID, departmentID, url, out parentID);
        }
        public string GetParentDeptCode(string deptID)
        {
            return departmentDao.GetParentDeptCode(deptID);

        }
        //判断是否有子部门
        public bool IsHaveSubDept(string deptID)
        {
            return departmentDao.IsHaveSubDept(deptID);
        }
        public string FilterDept(string comID, string deptID, string account)
        {
            string url = checkRight.GetRightUrl(account);//HttpContext.Current.Request.Url.AbsolutePath;
            return departmentDao.FilterDept(comID, deptID, account, url);
        }
    }
}
